﻿namespace Atomic.Plugins.Security.Application
{
    using System;
    using Atomic.Modules.Security;
    using Atomic.Plugins.Security.Domain;
    using Atomic.Plugins.Security.Repositories;

    /// <summary>
    /// 账户应用服务。
    /// </summary>
    public class AccountAppService : IAccountAppService
    {
        /// <summary>
        /// 会员服务。
        /// </summary>
        private readonly IMembershipService _membershipService = null;

        /// <summary>
        /// 认证服务。
        /// </summary>
        private readonly IAuthenticationService _authenticationService = null;

        /// <summary>
        /// 初始化用户应用服务。
        /// </summary>
        /// <param name="membershipService">会员服务。</param>
        /// <param name="authenticationService">认证服务。</param>
        public AccountAppService(IMembershipService membershipService, IAuthenticationService authenticationService)
        {
            this._membershipService = membershipService;
            this._authenticationService = authenticationService;
        }

        #region 登录用户

        /// <summary>
        /// 登录用户。
        /// </summary>
        /// <param name="accountNumber">账号。</param>
        /// <param name="password">密码。</param>
        /// <returns>操作状态。</returns>
        public LoginUserStatus Login(string accountNumber, string password)
        {
            var user = this._membershipService.GetUserByAccountNumber(accountNumber);

            if (user != null)
            {
                if (this.ValidateAccount(user.Account, password))
                {
                    this._authenticationService.SignIn(user, false);
                    return LoginUserStatus.Success;
                }

                return LoginUserStatus.Error;
            }
            else
            {
                return LoginUserStatus.UserInvalid;
            }
        }

        /// <summary>
        /// 验证账户信息。
        /// </summary>
        /// <param name="account">账户信息。</param>
        /// <param name="password">密码。</param>
        /// <returns>是否成功。</returns>
        public bool ValidateAccount(Account account, string password)
        {
            return account != null && account.EqualPassword(password);
        }

        #endregion

        #region 注销用户

        /// <summary>
        /// 注销用户。
        /// </summary>
        public void Logout()
        {
            this._authenticationService.SignOut();
        }

        #endregion
    }
}